import { CommonForm } from '@/pages/OrderModule/common/components/CommonForm';
import { useModal } from '@/pages/OrderModule/common/components/CommonModal';
import { useConfig } from '@/pages/OrderModule/common/hooks/useConfig';
import { getQuickSearchList, addQuickSearchOp, delQuickSearchOp, updateSortOp } from '@/pages/OrderModule/common/hooks/useConfig/services';
import { LeftOutlined } from '@ant-design/icons';
import { useLocation } from 'react-router-dom';
import { Button, Spin, Form, notification, message } from 'antd';
import CommonInput from "@/pages/OrderModule/common/components/CommonInput";
import { useMemo, useState, useEffect } from 'react';
import Style from './index.module.less';
import { QueryButton } from './queryButton';
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';

const pagesMap = {
  '/views/order/list': 'sys-order',//系统订单
  '/views/order/unpay': 'unpay-order',//待支付订单
  '/views/order/history': 'his-order',//历史订单
  '/views/order/ship': 'hot-order',//爆款打单
}

export function useQuiteSearch({ form, clearKey, handleSearch, checkFormChange, allLogisticsCompanyId = [] }) {
  // const {
  //   data = [],
  //   setData,
  //   save,
  //   getConfigLoading,
  // } = useConfig({
  //   code: 'quiteSearch',
  // });

  const [modalForm] = Form.useForm();
  const [data, setData] = useState([])
  const [quickSearchId, setQuickSearchId] = useState('');

  const location = useLocation();

  const page = useMemo(()=>{
   return pagesMap[location.pathname];
  }, [])

  useEffect(()=>{
    handelGetConfigList();
  }, [])

  useEffect(()=>{
    if(clearKey && quickSearchId){
      setQuickSearchId('');
    }
  }, [clearKey])
  
  // const handelDelete = (code) => {
  //   const newData = data.filter((item) => item !== code);
  //   setData(newData);
  //   save(newData);
  // };

  const handelGetConfigList = async () => {
    const { data, success} = await getQuickSearchList({ page });
    if(success){
      setData(data)
    }
  }

  const handelAdd = async (name) => {
    const value = form.getFieldsValue();
    if(value?.express?.logisticsCompanyId?.length){
      if(value.express.logisticsCompanyId.includes(-9999)){
        value.allLogisticsCompanyId = allLogisticsCompanyId;
      }
    }
    const { data, success} = await addQuickSearchOp({
      page,
      name,
      param: JSON.stringify(value)
    });
    if(success){
      handelGetConfigList();
    }
  }

  const handelDelete = async (configId) => {
    const { data, success} = await delQuickSearchOp({ configId });
    if(success){
      handelGetConfigList();
    }
  }

  const handleOpenModal = () => {
    if (data.length >= 20) {
      notification.error({
        message: '最多只能保存20个快捷查询条件',
        description: '请先删除已有快捷查询条件',
        duration: null
      });
      return;
    }
    const isChange = checkFormChange(form.getFieldsValue());
    if (isChange) {
      show({});
    } else {
      notification.error({
        message: '请设置选项再保存',
        duration: null
      });
    }

  };

  const [isExpand, setExpand] = useState(false);

  const list = useMemo(() => {
    return isExpand ? data : data.filter((_, index) => index < 4);
  }, [data, isExpand]);

  const { node, show, state, hide } = useModal({
    modal: {
      title: {
        title: '另存为快捷查询条件',
      },
      onOk() {
        modalForm.validateFields().then(({ input }) => {
          if(data.some(item=>item.name == input)){
            return message.info('快捷名称不可重复');
          }
          return handelAdd(input).then(()=>{
            hide();
            modalForm.resetFields();
          })
          const newData = [...data, state.input];
          if (data.includes(state.input)) {
            notification.error({
              message: '已有相同名称的快捷查询条件',
              duration: null
            });
            return;
          }
          setData(newData);
          save(newData);
          save(form.getFieldsValue(), { code: state.input });
          hide();
          modalForm.resetFields()
        })
      },
      onCancel() {
        hide();
        modalForm.resetFields()
      },
    },
    slot({ onChange }) {
      return (
        <CommonForm
          formProps={{
            onValuesChange(_, values) {
              onChange(values);
            },
            initialValues: {
              input: '',
            },
            form: modalForm,
          }}
          columns={[
            {
              name: 'input',
              Component: CommonInput,
              props: {
                placeholder: '必填，请输入快捷查询名称',
                maxLength: 10,
                'aria-required': true,
                showCount: true,
              },
              rules: [{ required: true, message: '请输入快捷查询名称' }]
            },
          ]}
        />
      );
    },
  });

  const handleDragEnd = async (result, provided) => {
    const { destination, source, draggableId } = result;
    if (!destination) {
        return;
    }
    if (destination.index === source.index) {
        return;
    }
    const newData = data.slice();
    // removing the item
    newData.splice(source.index, 1);
    // pushing in the new position
    newData.splice(destination.index, 0, data[source.index]);
    setData(newData);
    const arr = newData.map((item,sort)=>({
      sort,
      id: item.id,
    }))
    const { success } = await updateSortOp(arr);
    if(!success){
      // handelGetConfigList();
      setData(data)
    }
    // setData(newData);
    // save(newData);
};

const queryButtonProps = {
  form,
  quickSearchId,
  onClear: handelDelete,
  onClick(id){
    setQuickSearchId(id)
    handleSearch('quickSearch');
  }
}

  return {
    toggleSearchNode: (
      <>
        {node}
        <Button
          style={{ padding: '0 8px' }}
          onClick={handleOpenModal}
        >
          另存为快捷查询
        </Button>
      </>
    ),
    searchListNode: (
      <Spin spinning={false}>
        <DragDropContext onDragEnd={handleDragEnd}>
          <Droppable droppableId="droppable">
            {(provided, snapshot) => (
              <div
                ref={provided.innerRef}
                className={Style['quickly-query-wrapper']}
                {...provided.droppableProps}
              >

                {list.map((item, index) => (
                  <Draggable key={item?.id} draggableId={item?.id+''} index={index}>
                    {(provided, snapshot) => (
                      <div
                        ref={provided.innerRef}
                        {...provided.draggableProps}
                        {...provided.dragHandleProps}

                      >
                        <QueryButton key={index} item={item} {...queryButtonProps}>
                          {item}
                        </QueryButton>
                      </div>
                    )}
                  </Draggable>
                ))}
                {provided.placeholder}
              </div>
            )}
          </Droppable>

          {data.length > 4 &&
            <LeftOutlined className={Style['quickly-query-expander']} rotate={isExpand ? 90 : 270} onClick={() => setExpand(!isExpand)}></LeftOutlined>}
        </DragDropContext>
      </Spin>
    ),
  };
}
